<template>
  <view class="tn-safe-area-inset-bottom">
    <!-- 顶部状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <tn-nav-bar 
      :isBack="false" 
      :bottomShadow="false" 
      backgroundColor="none"
      :style="{ top: statusBarHeight + 'px' }"
    >
      <view class="custom-nav tn-flex tn-flex-col-center tn-flex-row-left">
        <!-- 图标logo -->
        <view class="custom-nav__back">
          <view class="logo-pic tn-shadow-blur"
                :style="{ 'background-image': 'url(' + user.avatar + ')'}">
            <view class="logo-image">
              <tn-badge backgroundColor="#E72F8C" :dot="true" :radius="16" :absolute="true" :translateCenter="false">
              </tn-badge>
            </view>
          </view>
          <!-- <view class="tn-icon-left"></view> -->
        </view>
<!--        &lt;!&ndash; 搜索框 &ndash;&gt;-->
<!--        <view class="custom-nav__search tn-flex tn-flex-col-center tn-flex-row-center ">-->
<!--          <view class="custom-nav__search__box tn-flex tn-flex-col-center tn-flex-row-left tn-color-gray&#45;&#45;dark tn-bg-gray&#45;&#45;light">-->
<!--            <view class="custom-nav__search__icon tn-icon-search"></view>-->
<!--            <view class="custom-nav__search__text tn-padding-left-xs">开启美好的一天</view>-->
<!--          </view>-->
<!--        </view>-->
        <view class="tn-margin-top tn-margin-left">
          <tn-tabs :list="scrollList" :current="current" @change="tabChange" activeColor="#000" bold="true"
                   :fontSize="36"></tn-tabs>
        </view>
      </view>

    </tn-nav-bar>

    <scroll-view 
      class="content-scroll" 
      scroll-y 
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      :style="{ paddingTop: `calc(${statusBarHeight}px + 90rpx)` }"
    >
      <!-- 刷新提示 -->
      <view v-if="isRefreshing" class="refresh-tip">
        <text class="tn-icon-refresh refresh-icon"></text>
        <text class="refresh-text">正在刷新...</text>
      </view>

      <!-- 文章列表 -->
      <block v-for="(item, index) in content" :key="index">
        <view class="article-shadow tn-margin" @click="detail(item.id)">
          <view class="tn-flex">
            <view class="tn-margin-sm tn-padding-top-xs" style="width: 100%;">
              <view class="tn-text-lg tn-text-bold clamp-text-2 tn-text-justify" style="min-height: 95rpx;">
                <view v-if="item.topicName != null && item.topicName !== '' " style="transform: translate(0,-5rpx);"
                      class="justify-content-item tn-tag-content__item tn-margin-right-xs tn-round tn-text-sm tn-text-bold" :class="[`tn-bg-${item.color}--light tn-color-${item.color}`]">
                  <text class="tn-tag-content__item--prefix">#</text> {{ item.topicName }}
                </view>
                <text class="">{{ item.title }}</text>
              </view>
              <view class="tn-padding-top-xs">
                <text class=" tn-text-sm tn-color-gray clamp-text-1">
                  {{ item.content }}
                </text>
              </view>
              <view class="tn-flex tn-flex-row-between tn-flex-col-between">
                <view class="justify-content-item tn-color-gray tn-text-center tn-color-gray--disabled" style="padding-top: 15rpx;">
                  <text class="tn-icon-footprint tn-padding-right-xs"></text>
<!--                  <text class="tn-padding-right">{{ item.collectionCount }}</text>-->
                  <text class="tn-padding-right">100</text>
                  <text class="tn-icon-like-lack tn-padding-right-xs"></text>
<!--                  <text class="">{{ item.likeCount }}</text>-->
                  <text class="">100</text>
                </view>
              </view>
            </view>
            <view class="image-pic tn-margin-sm" :style="'background-image:url(' + item.coverImage + ')'">
              <view class="image-article">
              </view>
            </view>
          </view>
        </view>
      </block>

      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="content.length > 0">
        <text v-if="hasMore">上拉加载更多</text>
        <text v-else>没有更多数据了</text>
      </view>
    </scroll-view>

    <!-- 悬浮发布按钮 -->
    <view class="floating-publish-btn" @click="goPublish">
      <view class="publish-btn-inner">
        <text class="tn-icon-add"></text>
      </view>
    </view>

    <view class="tn-padding-xl"></view>

  </view>
</template>

<script>
import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
import { getArticlePage,getDictData } from '@/api/article'
import {getFollowPage} from "@/api/fllow";
export default {
  name: 'TemplateCourse',
  mixins: [template_page_mixin],
  data() {
    return {
      current: 0,
      user:JSON.parse(uni.getStorageSync('user')),
      fllowUserId:[],
      scrollList: [],
      color:['red','blue','green','yellow','purplered','purple','brown'],
      content: [],
      isRefreshing: false, // 是否正在刷新
      hasMore: true, // 是否还有更多数据
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        title: null,
        content: null,
        coverImage: null,
        videoUrl: null,
        status: null,
        topicId: null,
        createTime: [],
        productId: null,
        isAllData:true,
        topicCode:null,
        authorId:null
      },
      statusBarHeight: 0,
    }
  },
  mounted() {
    this.findArticleList()
    this.findFllowList()
    this.queryTopic()
  },
  created() {
    const systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight
  },
  methods: {
    queryTopic(){
      getDictData(1,4,"article_topic").then(res=>{
        console.log(res)
        const list = res.data.data.list;
        //list遍历去掉对象中label = 首页与关注的值
        //遍历把每一个label 的值再放到对象中的name中去
        for (let i = 0; i < list.length; i++) {
          list[i].name = list[i].label
          list[i].code = list[i].value
        }
        this.scrollList = list
        console.log(this.scrollList)
      })
    },
    findFllowList(){
      const params = {
        pageNo:1,
        pageSize:10,
        userId:uni.getStorageSync("userId"),
        isAllData:true,
        status:0
      }
      getFollowPage(params).then(res=>{
        console.log("关注的人",res)
        res.data.data.list.forEach(res=>{
          this.fllowUserId.push(res.authorId)
        })
      })
    },
    formatTimestamp(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // getMonth() 返回 0-11
      const day = date.getDate();

      return `${year}年${month}月${day}日`;
    },
    findArticleList() {
        getArticlePage(this.queryParams).then(res => {
          // 遍历数组并添加 color 属性，随机选择一个颜色
          const listWithColor = res.data.data.list.map(item => ({
            ...item,
            color: this.getRandomColor()
          }));
          this.content = listWithColor;
          console.log(this.content)
          this.queryParams.topicCode = null
          this.queryParams.authorIdReq = null
        });
    },
    getRandomColor() {
      const randomIndex = Math.floor(Math.random() * this.color.length);
      return this.color[randomIndex];
    },
    // tab选项卡切换
    tabChange(index) {
      this.current = index
      console.log(index)
      if (index === 1){
        this.queryParams.authorIdReq = this.fllowUserId

        if (this.fllowUserId.length===0){
          this.queryParams.authorIdReq = [0]
        }
        console.log("关注")
        this.findArticleList()
        this.queryParams.authorIdReq = null
        return;
      }else if (index!==0){
        console.log(this.scrollList[this.current].code)
        this.queryParams.topicCode = this.scrollList[this.current].code
      } else {
        this.queryParams.topicCode = null
      }
      this.findArticleList()
    },
    detail(id){
      console.log(111)
      uni.navigateTo(
          {
            url: `/pages/article/index?id=${id}`
          }
      )
    },
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      try {
        // 重置页码
        this.queryParams.pageNo = 1
        await this.findArticleList()
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1000
        })
      } catch (error) {
        uni.showToast({
          title: '刷新失败',
          icon: 'error',
          duration: 1000
        })
      } finally {
        this.isRefreshing = false
      }
    },

    // 上拉加载更多
    async onLoadMore() {
      if (!this.hasMore) return
      
      try {
        this.queryParams.pageNo++
        const res = await getArticlePage(this.queryParams)
        const newList = res.data.data.list.map(item => ({
          ...item,
          color: this.getRandomColor()
        }))
        
        // 如果新数据长度小于pageSize，说明没有更多数据了
        if (newList.length < this.queryParams.pageSize) {
          this.hasMore = false
        }
        
        this.content = [...this.content, ...newList]
      } catch (error) {
        this.queryParams.pageNo-- // 加载失败，页码回退
        uni.showToast({
          title: '加载失败',
          icon: 'error',
          duration: 1000
        })
      }
    },

    // 修改原有的findArticleList方法
    async findArticleList() {
      try {
        const res = await getArticlePage(this.queryParams)
        // 重置数据
        const listWithColor = res.data.data.list.map(item => ({
          ...item,
          color: this.getRandomColor()
        }))
        this.content = listWithColor
        this.hasMore = listWithColor.length >= this.queryParams.pageSize
        this.queryParams.topicCode = null
        this.queryParams.authorIdReq = null
      } catch (error) {
        console.error('获取文章列表失败:', error)
        throw error
      }
    },
    goPublish() {
      uni.navigateTo({
        url: '/components/publish/publish'
      })
    },
  }
}
</script>

<style lang="scss" scoped>
@import '@/static/css/templatePage/custom_nav_bar.scss';

/* 自定义导航栏内容 start */
.custom-nav {
  height: 100%;

  &__back {
    margin: auto 5rpx;
    font-size: 40rpx;
    margin-right: 10rpx;
    margin-left: 30rpx;
    flex-basis: 5%;
  }

  &__search {
    flex-basis: 60%;
    width: 100%;
    height: 100%;

    &__box {
      width: 100%;
      height: 70%;
      padding: 10rpx 0;
      margin: 0 30rpx;
      border-radius: 60rpx 60rpx 0 60rpx;
      font-size: 24rpx;
    }

    &__icon {
      padding-right: 10rpx;
      margin-left: 20rpx;
      font-size: 30rpx;
    }

    &__text {
      color: #AAAAAA;
    }
  }
}

.logo-image {
  width: 60rpx;
  height: 60rpx;
  position: relative;
  margin-top: -15rpx;
}

.logo-pic {
  background-size: cover;
  background-repeat: no-repeat;
  // background-attachment:fixed;
  background-position: top;
  border-radius: 50%;
}

/* 自定义导航栏内容 end */

/* 资讯主图 start*/
.image-article {
  border-radius: 8rpx;
  border: 1rpx solid #F8F7F8;
  width: 250rpx;
  height: 200rpx;
  position: relative;
}

.image-pic {
  background-size: cover;
  background-repeat: no-repeat;
  // background-attachment:fixed;
  background-position: top;
  border-radius: 10rpx;
}

.article-shadow {
  border-radius: 15rpx;
  box-shadow: 0rpx 0rpx 50rpx 0rpx rgba(0, 0, 0, 0.07);
}

/* 文字截取*/
.clamp-text-1 {
  -webkit-line-clamp: 1;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  overflow: hidden;
}

.clamp-text-2 {
  -webkit-line-clamp: 2;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  overflow: hidden;
}

/* 标签内容 start*/
.tn-tag-content {
  &__item {
    display: inline-block;
    line-height: 35rpx;
    padding: 5rpx 25rpx;

    &--prefix {
      padding-right: 10rpx;
    }
  }
}

/* 标签内容 end*/

/* 底部tabbar start*/
.footerfixed {
  position: fixed;
  width: 100%;
  bottom: 0;
  z-index: 999;
  background-color: #FFFFFF;
  box-shadow: 0rpx 0rpx 30rpx 0rpx rgba(0, 0, 0, 0.07);
}

.tabbar {
  display: flex;
  align-items: center;
  min-height: 110rpx;
  justify-content: space-between;
  padding: 0;
  height: calc(110rpx + env(safe-area-inset-bottom) / 2);
  padding-bottom: calc(env(safe-area-inset-bottom) / 2);
}

.tabbar .action {
  font-size: 22rpx;
  position: relative;
  flex: 1;
  text-align: center;
  padding: 0;
  display: block;
  height: auto;
  line-height: 1;
  margin: 0;
  overflow: initial;
}

.bar-center {
  animation: suspension 3s ease-in-out infinite;
}

@keyframes suspension {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-0.8rem);
  }
}

.tabbar .action .bar-icon {
  width: 100rpx;
  position: relative;
  display: block;
  height: auto;
  margin: 0 auto 10rpx;
  text-align: center;
  font-size: 42rpx;
  // line-height: 50rpx;
}

.tabbar .action .bar-icon image {
  width: 50rpx;
  height: 50rpx;
  display: inline-block;
}

.tabbar .action .bar-circle {
  position: relative;
  display: block;
  margin: 0rpx auto 0rpx;
  text-align: center;
  font-size: 60rpx;
  line-height: 100rpx;
  background-color: #FBBF18;
  width: 100rpx !important;
  height: 100rpx !important;
  overflow: hidden;
  border-radius: 50%;
  box-shadow: 0px 10px 30px rgba(70, 23, 129, 0.12),
  0px -8px 40px rgba(255, 255, 255, 1),
  inset 0px -10px 10px rgba(70, 23, 129, 0.05),
  inset 0px 10px 20px rgba(255, 255, 255, 1);
  box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(251, 191, 24, 0.5);
}

.tabbar .action .bar-circle image {
  width: 100rpx;
  height: 100rpx;
  display: inline-block;
  margin: 0rpx auto 0rpx;
}

/* 流星+悬浮 */
.nav-index-button {
  animation: suspension 3s ease-in-out infinite;
  z-index: 999999;


  &__content {
    position: absolute;
    width: 100rpx;
    height: 100rpx;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    &--icon {
      width: 100rpx;
      height: 100rpx;
      font-size: 60rpx;
      border-radius: 50%;
      margin-bottom: 18rpx;
      position: relative;
      z-index: 1;
      transform: scale(0.85);

      &::after {
        content: " ";
        position: absolute;
        z-index: -1;
        width: 100%;
        height: 100%;
        left: 0;
        bottom: 0;
        border-radius: inherit;
        opacity: 1;
        transform: scale(1, 1);
        background-size: 100% 100%;
        // background-image: url(https://resource.tuniaokj.com/images/cool_bg_image/icon_bg6.png);
      }
    }
  }

  &__meteor {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100rpx;
    height: 100rpx;
    transform-style: preserve-3d;
    transform: translate(-50%, -50%) rotateY(75deg) rotateZ(10deg);

    &__wrapper {
      width: 100rpx;
      height: 100rpx;
      transform-style: preserve-3d;
      animation: spin 20s linear infinite;
    }

    &__item {
      position: absolute;
      width: 100rpx;
      height: 100rpx;
      border-radius: 1000rpx;
      left: 0;
      top: 0;

      &--pic {
        display: block;
        width: 100%;
        height: 100%;
        background: url(https://resource.tuniaokj.com/images/cool_bg_image/arc1.png) no-repeat center center;
        background-size: 100% 100%;
        animation: arc 4s linear infinite;
      }
    }
  }
}


@keyframes suspension {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-0.6rem);
  }
}

@keyframes spin {
  0% {
    transform: rotateX(0deg);
  }

  100% {
    transform: rotateX(-360deg);
  }
}

@keyframes arc {
  to {
    transform: rotate(360deg);
  }
}

.content-scroll {
  flex: 1;
  height: calc(100vh - 100rpx); /* 减去顶部导航栏的高度 */
}

.refresh-tip {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
  
  .refresh-icon {
    margin-right: 10rpx;
    animation: rotate 1s linear infinite;
  }
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.status-bar {
  width: 100%;
  background: #fff;
  position: fixed;
  top: 0;
  z-index: 1000;
}

.content-scroll {
  height: calc(100vh - env(safe-area-inset-bottom));
  box-sizing: border-box;
}

.floating-publish-btn {
  position: fixed;
  right: 30rpx;
  bottom: calc(120rpx + env(safe-area-inset-bottom)); /* 避免底部导航栏遮挡 */
  z-index: 99;
  
  .publish-btn-inner {
    width: 100rpx;
    height: 100rpx;
    background: linear-gradient(45deg, #FF85AD, #FFA6C1);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 16rpx rgba(255, 133, 173, 0.4);
    transition: all 0.3s ease;
    
    .tn-icon-add {
      font-size: 50rpx;
      color: #fff;
    }
    
    &:active {
      transform: scale(0.9);
      box-shadow: 0 2rpx 8rpx rgba(255, 133, 173, 0.3);
    }
  }
}

/* 添加动画效果 */
@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10rpx);
  }
}

.floating-publish-btn {
  animation: float 3s ease-in-out infinite;
}
</style>
